package cn.fl.project.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.project.api.IProjectContractMakeApiService;
import cn.fl.project.excel.PrjContBatchMakeExcel;
import cn.fl.project.excel.PrjContBatchMakeExcelImportParam;
import cn.fl.project.service.IPrjContBatchMakeService;
import cn.fl.project.transform.PrjContCreatRecVOTransform;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.fl.project.dto.PrjContCreatRecDTO;
import cn.fl.project.vo.PrjContCreatRecVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * @Description: 项目合同生成记录表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class
PrjContBatchMakeServiceImpl implements IPrjContBatchMakeService {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(PrjContBatchMakeServiceImpl.class);

    /**
     *
     */
    @Autowired
    private IProjectContractMakeApiService projectContractMakeApiService;


    @Override
    public boolean modify(PrjContCreatRecVO entity) throws BaseException{
        if(null == entity){
            BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        PrjContCreatRecDTO prjContCreatRecDTO = projectContractMakeApiService.selectById(entity.getId());
        prjContCreatRecDTO.setForceSign(entity.getForceSign());
        prjContCreatRecDTO.setCfgCd(entity.getCfgCd());
        return this.projectContractMakeApiService.modify(prjContCreatRecDTO);
    }

    @Override
    public String addContByBatchNumber(String batchNumber) throws BaseException {

        return projectContractMakeApiService.addContractByBatchNumber(batchNumber,String.valueOf(CurrentThreadContext.getCurrentUserId()));
    }

    @Override
    public boolean addContractByLogId(Long logId) throws BaseException {
        return projectContractMakeApiService.addContractByLogId(logId,String.valueOf(CurrentThreadContext.getCurrentUserId()));
    }

    @Override
    public boolean addContract(Long logId, List<String> tmplateIds) throws BaseException {
        return projectContractMakeApiService.addContract(logId,tmplateIds,String.valueOf(CurrentThreadContext.getCurrentUserId()));
    }


    @Override
    public String addBatchByUpload(MultipartHttpServletRequest multipartRequest) throws BaseException {
        String batchNumber =System.nanoTime()+"";
        BaseLogUtils.info(logger, "uploadContract", "合同生成文件上传开始", CurrentThreadContext.getCurrentUserName());
        List<PrjContCreatRecVO> prjContBatchMakeVos = Lists.newArrayList();
        try {

            Iterator<String> iter = multipartRequest.getFileNames();
            // 如果没有文件 抛出异常
            if (!iter.hasNext()) {
                BaseLogUtils.info(logger, "fileUpload", "文件上传失败,未选中文件内容.", CurrentThreadContext.getCurrentUserName());
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "请选择要上传的文件!");
            }
            //只取第一个文件
            MultipartFile f = multipartRequest.getFile(iter.next());

            //限制大小为100k
            if(f.getSize()>100000){
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "请上传小于100kb的文件!");
            }
            String fileName = f.getOriginalFilename().toLowerCase();
            if(!fileName.endsWith(".xlsx")  && !fileName.endsWith(".xls")) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "文件格式不对，请选择xls或xlsx格式！!");
            }

            if(f.getSize()==0){
                BaseLogUtils.info(logger, "fileUpload", "文件上传失败,未选中文件内容.", CurrentThreadContext.getCurrentUserName());
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "请选择要上传的文件!");
            }
            List<PrjContBatchMakeExcel> prjContBatchMakeExcels = ExcelImportUtil.importExcel(f.getInputStream(), PrjContBatchMakeExcel.class, PrjContBatchMakeExcelImportParam.build1101Params());
            for (PrjContBatchMakeExcel prjContBatchMakeExcel : prjContBatchMakeExcels) {
                //如果合同编号是空的不处理
                if(StringUtils.isBlank(prjContBatchMakeExcel.getContractNumber())){
                    continue;
                }else{
                    //继续
                }
                PrjContCreatRecVO prjContBatchMakeVo = new PrjContCreatRecVO();
                prjContBatchMakeVo.setCrtTm(new Date());
                prjContBatchMakeVo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                prjContBatchMakeVo.setSysCd(CurrentThreadContext.getCurrentSysCd());
                prjContBatchMakeVo.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
                prjContBatchMakeVo.setBatchNo(batchNumber);
                prjContBatchMakeVo.setLsCntNo(prjContBatchMakeExcel.getContractNumber());
                prjContBatchMakeVos.add(prjContBatchMakeVo);
            }
            if(CollectionUtils.isEmpty(prjContBatchMakeVos)){
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "上传可用数据为空");
            }
            String batchNo = projectContractMakeApiService.addBatchByUpload(PrjContCreatRecVOTransform.toDTOList(prjContBatchMakeVos));

            BaseLogUtils.info(logger, "upload", "合同生成文件上传结束", CurrentThreadContext.getCurrentUserName());
            return batchNo;
        } catch (BaseException ex) {
            BaseLogUtils.info(logger, "fileUpload", "文件上传失败.ERROR", CurrentThreadContext.getCurrentUserName(), ex);
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, ex.getMessage());
        } catch (Exception ex) {
            BaseLogUtils.error(logger, "fileUpload", "文件上传失败,系统错误.ERROR", CurrentThreadContext.getCurrentUserName(), ex);
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "系统异常!");
        }
    }

    @Override
    public List<PrjContCreatRecVO> selectListByBatchNumber(String batchNumber) throws BaseException {
        List<PrjContCreatRecDTO> prjContCreatRecDTOS = projectContractMakeApiService.selectListByBatchNumber(batchNumber);
        List<PrjContCreatRecVO> list = PrjContCreatRecVOTransform.toVOList(prjContCreatRecDTOS);
        return list;
    }

    @Override
    public Pager searchListPage(Pager page) {
        Pager pager = projectContractMakeApiService.searchListPage(page);
        return pager;
    }
}
